package com.example.forum.controller;

import com.example.forum.dto.UpdateUser;
import com.example.forum.dto.UserCreate;
import com.example.forum.entity.Token;
import com.example.forum.entity.User;
import com.example.forum.entity.Visitor;
import com.example.forum.interceptor.UserContext;
import com.example.forum.mapper.TokenMapper;
import com.example.forum.mapper.UserMapper;
import com.example.forum.util.JsonResult;
import lombok.val;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import javax.xml.ws.BindingType;
import java.io.File;
import java.io.IOException;
import java.net.BindException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;

@CrossOrigin
@RestController
public class UserController {
    @Resource
    UserMapper userMapper;
    @Resource
    TokenMapper tokenMapper;

    @Value("${user.dir}/uploads/")
    private String uploadPath;

//注册账号
    @PostMapping("/api/user/create")
    public JsonResult<Object> UserCreate(@Valid UserCreate userCreate){
        String nickname=userCreate.getNickname();
        String  password=userCreate.getPassword();
        String username=userCreate.getUsername();
        //去判断账户名username是否存在,存在返回user，
        User user=userMapper.selectUser(username);
        System.out.println(user);
        if(!(user==null)){
            return new JsonResult<>("Error","账户已存在");
        }
        //不存在执行新增，再次查询返回id，存入token中的userId 此处待设置头像
        User user1=User.builder().nickname(nickname).password(password).username(username).avatar(getAvatar()).build();
        int insert=userMapper.insert(user1);
        System.out.println(insert);
        if(insert==1){
            String token= UUID.randomUUID().toString().replaceAll("-","");
            System.out.println(token);
            int id=userMapper.selectUser(username).getId();
            Token tokenInsert=Token.builder().userId(id).token(token).build();
            //此处为直接新增token。bug 理论上：新增前应该把重复或者即将重复的userId记录先删除（查询+删除+新增）
            int a=tokenMapper.insert(tokenInsert);
            if(a==1){
                Map<String,Object> data=new HashMap<>();
                data.put("token",token);
                return new JsonResult<>("",data);
            }
            return new JsonResult<>("error","token新增错误，未知错误");

        }
        return new JsonResult<>("error","userCreate新增错误，未知错误");
    }

    //更换手机号，昵称， 密码
    @PostMapping("/api/user/update")
    public JsonResult<Object> update(@Valid UpdateUser updateUser) {

        String password=updateUser.getPassword();
        System.out.println("密码"+password);
        if(password!=null&&(!password.equals(""))){
            Pattern p= Pattern.compile("(?=.*?[a-zA-Z])(?=.*?[0-9]).{2,16}");
            Matcher m =p.matcher(password);
            if(!m.matches()){
                return new JsonResult<>("ERROR","密码格式不对");
            }

        }
        try {
            System.out.println(UserContext.getUser());
            String username=UserContext.getUser().getUsername();
            String mobile=updateUser.getMobile();
            String nickname= updateUser.getNickname();
            System.out.println("昵称： "+nickname);
            System.out.println("密码： "+password);
            System.out.println("手机： "+mobile);
            int id=UserContext.getUser().getId();
            User user1=userMapper.selectUserByid(id);
            if(mobile==null|| mobile.isEmpty()){
                mobile=user1.getMobile();
            }
            if(nickname==null||nickname.isEmpty()){
                nickname=user1.getNickname();
            }
            if(password==null||password.isEmpty()){
                password=user1.getPassword();
            }


            User user=User.builder().mobile(mobile).nickname(nickname).password(password).build();
            int i= userMapper.update(username,user);
            if(i!=1){
                return new JsonResult<>("error","更改失败");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        Map<String,String>data=new HashMap<>();
        data.put("","更改 成功");
        return new JsonResult<>("success",data);

    }
    @GetMapping("api/user/whoami")
    public JsonResult<Object> whoami(){
        String username=UserContext.getUser().getUsername();
        User user =userMapper.selectUser(username);
        Map<String,Object>data=new HashMap<>();
        data.put("avatar",user.getAvatar());
        data.put("createdAt",user.getCreatedAt());
        data.put("id",user.getId());
        data.put("mobile",user.getMobile());
        data.put("nickname",user.getNickname());
        data.put("username",user.getUsername());
        return new JsonResult<>("Success",data);
    }
    //上传头像

        @PostMapping("/api/upload/avatar")
        public JsonResult<Object>avatar(@RequestParam("avatar") MultipartFile file)throws IOException,InterruptedException{
            if(file.isEmpty()){
                return new JsonResult<>("error","没有上传文件");
            }
            //找分隔符，获取文件后缀名  or  file.getContentType()
            int index=file.getOriginalFilename().lastIndexOf(".");
            String extname=file.getOriginalFilename().substring(index+1).toLowerCase();
            //格式只允许以下四种格式
            String allowImgFormat="png,jpg,jpeg,gif,bmp";
            System.out.println(extname);
            if(!allowImgFormat.contains(extname)){
                return new JsonResult<>("error","文件类型不支持");
            }

            //获取简单时间格式，从而获得年月文件夹，动态生成子目录
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy/MM/");
            String subPath=simpleDateFormat.format(new Date());
            //创建年月文件夹
            File dir=new File(uploadPath+subPath);
            if(!dir.exists()){
                dir.mkdirs();
            }
            //定义文件名，创建文件
            String saveName= subPath+UUID.randomUUID().toString().replaceAll("-","")+"."+extname;
            File save=new File(uploadPath+saveName);
            //参数file数据文件传输到绝对路径
            file.transferTo(save.getAbsoluteFile());
            Map <String,String>data=new HashMap<>();
            System.out.println(saveName);
            String username=UserContext.getUser().getUsername();
            User user =User.builder().avatar("http://127.0.0.1:8080/static/uploads/"+saveName).build();
            int i=userMapper.update(username,user);
            if(i!=1){
                System.out.println("上传失败");
                return new JsonResult<>("error2","上传失败");
            }
            data.put("","上传成功");
            data.put("avatar","http://127.0.0.1:8080/static/uploads/"+saveName);
            //save db saveName 存到数据库，只需要记载后续路径
            return new JsonResult<>("Success",data);
        }
    //获取访客，登录注册后，更改用户信息（例如把username改成username1，再改回来），从而获取更新时间次序。


    @GetMapping("/api/user/visitor")
    public JsonResult<Object>getVisitor(){
        List<Visitor>data=userMapper.visitor();

        return new JsonResult<>("",data);
    }
    public String getAvatar(){
        String[] str2={"http://xueba.it266.com:8081/default/avatar/3.jpeg","http://xueba.it266.com:8081/2022/12/07/222815fc758c4adaaf3776a5201aa99c.jpeg",
                "http://127.0.0.1:8080/static/uploads/2022/12/53e3d743be3c46d3b31511c7a41a448d.png","http://127.0.0.1:8080/static/uploads/2022/12/ccd006c3f0fe45bc83f594c5a0221fd2.png"};
        val i = (int) (Math.random() * 4);
//        String []a= new String[]{"a","as", "s"};
        return str2[i];
    }

}
